
package cyf.Filter;

import cyf.Login.bean.AdminVO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.StringTokenizer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 登录过滤器 检查session
 */
@WebFilter(urlPatterns = {"/manage/*","/ParkManage/*"})
public class CheckFilter implements Filter {
    protected FilterConfig filterConfig = null;

    private String redirectURL = null;

    private List notCheckURLList = new ArrayList();

    private String sessionKey = null;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        redirectURL = filterConfig.getInitParameter("redirectURL");
        sessionKey = filterConfig.getInitParameter("checkSessionKey");

        String notCheckURLListStr = filterConfig
                .getInitParameter("notCheckURLList");
        if (notCheckURLListStr != null) {
            StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");
            notCheckURLList.clear();
            while (st.hasMoreTokens()) {
                notCheckURLList.add(st.nextToken());
            }
        }

    }

    /**
     * 用来保护后台页面 不登陆就跳转到登录页面
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest _request = (HttpServletRequest) request;
        HttpServletResponse _response = (HttpServletResponse) response;
        HttpSession httpSession = _request.getSession();
        Object object = httpSession.getAttribute("Admin");
        if(object!=null && object instanceof AdminVO){
            chain.doFilter(request,response);
            return;
        }else{
            _response.sendRedirect("http://localhost:8888/home/hello");
            return;
        }
    }

    @Override
    public void destroy() {
        notCheckURLList.clear();
    }
}

